import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import Notify from '@vant/weapp/notify/notify';
import {clearUserLocalStorage} from "../../../../utils/util";

const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        customer_id: undefined,
        order_status:[],

        min_date: undefined,
        max_date: undefined,

        show_select: false,

        valid_cps_status_text: {
            'undefined':'',
            '0': '未下单',
            '1': '进行中',
            '2': '已达标',
            '3': '已确认',
            '-1': '失败',
            '-2': '超时关闭'
        },
        customers: [], //商户
        markers: [], //地图上的标记
        longitude: 0, //经纬度
        latitude: 0,
        access_token: undefined,
        user: undefined,
        valid_cps_status: undefined,
        view_public: 0,

        show_search_bar: true,
        search_word:'',

        //弹出框的ID和备注名
        popup_remark_id: 0,
        popup_remark_name: '',
        popup_idx: 0,

        //页码
        page: 0,
        //每页条目
        page_size: 10,

        show_calendar: true, //显示日历
        date: '',

        formatter(day) {
            return day
        },



    },


    /**
     * 点击打开
     */
    onChange(event) {
        console.log(event.detail)
        this.setData({
            activeNames: event.detail,
        });
    },
    call_mobile(e) {
        let mobile = e.currentTarget.dataset.mobile
        wx.makePhoneCall({
            phoneNumber: mobile,
            success: function () {
                console.log("拨打电话成功！")
            },
            fail: function () {
                console.log("拨打电话失败！")
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        let that = this
        let now = (new Date().getTime()) / 1000;
        let expiration_time = wx.getStorageSync('expiration_time')
        let group = wx.getStorageSync('role')

        if (group!=='销售员') {
            clearUserLocalStorage()
            expiration_time = 0
        }

        if (now > expiration_time) {
            wx.reLaunch({
                url: '/pages/login/login',
            })
        }



        let access_token =  wx.getStorageSync('access_token')
        let user = wx.getStorageSync('user')

        let data ={
            'access_token': access_token,
            'user': user,
        }


        let min_date = new Date();
        min_date.setMonth(min_date.getMonth() - 1);
        min_date.setDate(1);
        min_date.setHours(0, 0, 0, 0);

        this.setData({
            min_date: min_date.getTime(),
            max_date: (new Date()).getTime(),
        })


        let order_status = wx.getStorageSync('order_status')
        let result = order_status.reduce((acc, item) => {
            acc[item.day] = item;
            return acc;
        }, {});

        this.setData({
            formatter: function(day) {
                const year = day.date.getFullYear()
                const month = String(day.date.getMonth() + 1).padStart(2, '0');
                const date = String(day.date.getDate()).padStart(2, '0');
                let key =year + '-' + month  + '-' + date;
                //console.log(key)
                if (key in result) {

                    let status = result[key]
                    day.topInfo = status.day_count
                    day.bottomInfo = status.day_total_pay_price + '元'
                    if (status.day_total_pay_price<150) {
                        day.className = 'red-yellow';
                    } else if (status.day_total_pay_price>=150) {
                        day.className = 'red-yellow';
                    }
                    if (status.day_total_pay_price>200) {
                        day.className = 'orange-brown';
                    }
                }


                return day;
            }
        })


        //接收上级传递的参数
        // const eventChannal = this.getOpenerEventChannel();
        // eventChannal.on('orderAll', function (res) {
        //     let orderAll = JSON.parse(res)
        //     this_.setData({
        //         orderAll
        //     })
        //     console.log(orderAll)
        // })

    },

    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        let that = this
        setTimeout(function () {
            //that.get_order_status().then(r => {

            //})
        }, 2000);
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        let that = this
        //this.get_order_status()

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    async get_order_status() {
        let that = this
        wx.p.request({
            url: app.globalData.API + '/sales/index/get-customer-month-status',
            header: {
                'Content-Type': 'application/json',
                "x-api-key": this.data.access_token,
            },
            method: "POST",
            data: {
                customer_id: that.data.customer_id,
            },
            success(res) {
                if (res.data.code === 200) {
                    let order_status = res.data.data.data
                    let count = res.data.data.count
                    if (count >0) {
                        that.setData({
                            order_status: order_status
                        })
                    }

                } else if (res.data.code === 0) {
                    clearUserLocalStorage()
                    wx.reLaunch({
                        url: "/pages/login/login"
                    })
                }
            },
            fail() {
                wx.showToast({
                    title: '请求错误',
                    icon: 'error',
                    duration: 2000
                })
            },
        })
    },
})
